package dvb.reddwarf.profiler;

import java.util.concurrent.atomic.AtomicLong;

/**
 * Task record - summary information about executed tasks of certain type.
 * @author dvb
 */
class TaskRecord {

    /**
     * total count of tasks of this type
     */
    final AtomicLong totalCount = new AtomicLong();
    /**
     * count of succeded tasks of this type
     */
    final AtomicLong successfulCount = new AtomicLong();
    /**
     * total time that all task of this type were executed
     */
    final AtomicLong totalTime = new AtomicLong();
    /**
     * total time that successfull task of this type were executed
     */
    final AtomicLong successfulTime = new AtomicLong();
    /**
     * name of task class
     */
    final String type;

    public TaskRecord(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append(" c:").append(totalCount.longValue()).append("\t");
        if (totalCount.longValue() > 0) {
            sb.append("f:").append(PeriodicProfilerListener.DECIMAL_FORMAT.format(getFailedPercent())).append("%\t");
            final long successfulCountNow = successfulCount.longValue();
            sb.append("t:").append(successfulCountNow>0?successfulTime.longValue()/successfulCountNow:0).append(" ms\t");
            sb.append("s:").append(totalTime.longValue()).append(" ms\t");
        }
        sb.append(type);
        return sb.toString();
    }

    double getFailedPercent() {
        return (totalCount.longValue() - successfulCount.longValue()) * 100.0 / totalCount.longValue();
    }

    public void report(long runningTime, boolean wasSuccessful) {
        totalCount.incrementAndGet();
        totalTime.addAndGet(runningTime);

        if (wasSuccessful) {
            successfulCount.incrementAndGet();
            successfulTime.addAndGet(runningTime);
        }
    }
}
